package com.dankegongyu.lib.common.paging;

import com.dankegongyu.lib.common.base.BaseViewModel;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

/**
 * @author wpq
 * @version 1.0
 */
public abstract class BasePagingViewModel<M extends BasePagingModel, T> extends BaseViewModel implements BasePagingModelListener<T> {

    private M mPagingModel;
    private final MutableLiveData<PagingData<T>> pagingDataLiveData = new MutableLiveData<>();
    private final MutableLiveData<PagingState> pagingStateLiveData = new MutableLiveData<>();

    public BasePagingViewModel() {
        mPagingModel = createPagingModel();
        init();
    }

    protected abstract M createPagingModel();

    public M getPagingModel() {
        return mPagingModel;
    }

    public MutableLiveData<PagingData<T>> getPagingDataLiveData() {
        return pagingDataLiveData;
    }

    public MutableLiveData<PagingState> getPagingStateLiveData() {
        return pagingStateLiveData;
    }

    protected abstract void init();

    public void refresh() {
        if (mPagingModel != null) {
            mPagingModel.refresh();
        }
    }

    public void loadMore() {
        if (mPagingModel != null) {
            mPagingModel.loadMore();
        }
    }

    @Override
    public void onPagingLoadSuccess(@NonNull BasePagingModel model, @NonNull PagingData<T> pagingData) {
        if (model == this.mPagingModel) {
            if (pagingData.getTotalCount() <= 0) {
                pagingStateLiveData.postValue(PagingState.EMPTY);
            } else {
                pagingDataLiveData.postValue(pagingData);
                if (pagingData.hasNextPage()) {
                    pagingStateLiveData.postValue(PagingState.SUCCESS);
                } else {
                    pagingStateLiveData.postValue(PagingState.NO_MORE_DATA);
                }
            }
        }
    }

    @Override
    public void onPagingLoadFailure(@NonNull BasePagingModel model, String errorMessage, boolean isFirstPage) {
        if (model == this.mPagingModel) {
            if (isFirstPage) {
                pagingStateLiveData.postValue(PagingState.ERROR.setMessage(errorMessage));
            } else {
                pagingStateLiveData.postValue(PagingState.LOAD_MORE_FAILED.setMessage(errorMessage));
            }
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (mPagingModel != null) {
            mPagingModel.onDestroy();
        }
    }

}
